package com.jiuyin.dianjing.ui.activity.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.SectionsPagerAdapter;
import com.jiuyin.dianjing.receiver.OrderReceiver;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.activity.search.SearchGameInfoActivity;
import com.jiuyin.dianjing.ui.fragment.main.FragmentFirst;
import com.jiuyin.dianjing.ui.fragment.main.FragmentThird;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.app.HelperApplication.getContext;
import static com.jiuyin.dianjing.constant.AppConstant.ACTION_NEED_LOGIN;
import static com.jiuyin.dianjing.constant.AppConstant.ACTION_ORDER_UPLOAD;

public class MainDrawerActivity extends BaseActivity {
    private final List<Fragment> listFragment = new ArrayList<>();
    private final CusReceiver mCusReceiver = new CusReceiver();
    private final OrderReceiver mOrderReceiver = new OrderReceiver();
    @BindView(R.id.vp_view_container)
    ViewPager mViewPager;
    private final BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_first:
                    mViewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_second:
                    mViewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_third:
                    mViewPager.setCurrentItem(2);
                    return true;
                case R.id.navigation_four:
                    mViewPager.setCurrentItem(3);
                    return true;
                case R.id.navigation_five:
                    mViewPager.setCurrentItem(4);
                    return true;
                default:
                    break;
            }
            return false;
        }
    };
    @BindView(R.id.bottom_nav_view)
    BottomNavigationView mBottomNavView;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.nav_view)
    NavigationView mNavView;
    private SectionsPagerAdapter mSectionsPagerAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        registerReceiver();
        listFragment.add(new FragmentFirst());
        listFragment.add(new FragmentFirst());
        listFragment.add(new FragmentThird());
        listFragment.add(new FragmentFirst());
        listFragment.add(new FragmentFirst());
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), listFragment);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                mBottomNavView.setSelectedItemId(mBottomNavView.getMenu().getItem(position).getItemId());
            }
        });
        mViewPager.setOffscreenPageLimit(listFragment.size());
        mBottomNavView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    @Override
    protected void initView() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawerLayout, R.string.app_name, R.string.app_name) {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                //可以重新侧滑方法,该方法实现侧滑动画,整个布局移动效果
                //获取mDrawerLayout中的第一个子布局，也就是布局中的RelativeLayout
                //获取抽屉的view
                View mContent = mDrawerLayout.getChildAt(0);
                float scale = 1 - slideOffset;
                float endScale = 0.8f + scale * 0.2f;
                float startScale = 1 - 0.3f * scale;

                //设置左边菜单滑动后的占据屏幕大小
                drawerView.setScaleX(startScale);
                drawerView.setScaleY(startScale);
                //设置菜单透明度
                drawerView.setAlpha(0.6f + 0.4f * (1 - scale));

                //设置内容界面水平和垂直方向偏转量
                //在滑动时内容界面的宽度为 屏幕宽度减去菜单界面所占宽度
                mContent.setTranslationX(drawerView.getMeasuredWidth() * (1 - scale));
                //设置内容界面操作无效（比如有button就会点击无效）
                mContent.invalidate();
                //设置右边菜单滑动后的占据屏幕大小
                mContent.setScaleX(endScale);
                mContent.setScaleY(endScale);
            }
        };

        toggle.syncState();
        mDrawerLayout.addDrawerListener(toggle);
        mNavView.setItemIconTintList(null);
        //设置item的点击事件
        mNavView.setNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            switch (id) {
                case R.id.nav_quit:
                    ToastUtil.showShort(R.string.setting_quit);
                    LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(ACTION_NEED_LOGIN));
                    break;
                case R.id.nav_gallery:
                    ToastUtil.showShort("nav_gallery");
                    goTargetActivity(SearchGameInfoActivity.class);
                    break;
                case R.id.nav_slideshow:
                    ToastUtil.showShort("nav_slideshow");
                    goTargetActivity(SearchGameInfoActivity.class);
                    break;
                case R.id.nav_tools:
                    ToastUtil.showShort("nav_tools");
                    goTargetActivity(SearchGameInfoActivity.class);
                    break;
                default:
                    break;
            }
            mDrawerLayout.closeDrawer(GravityCompat.START);
            return true;
        });
    }

    /**
     * 主页按返回键返回桌面，程序不退出再次点击图标直接进入程序
     * 类似支付宝效果
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        } else {
            return false;
        }
        return true;
    }

    protected void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_NEED_LOGIN);
        intentFilter.addAction(ACTION_ORDER_UPLOAD);
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(mCusReceiver, intentFilter);
        IntentFilter orderIntentFilter = new IntentFilter();
        orderIntentFilter.addAction(ACTION_ORDER_UPLOAD);
        registerReceiver(mOrderReceiver, orderIntentFilter);
    }

    protected void unRegisterReceiver() {
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mCusReceiver);
        unregisterReceiver(mOrderReceiver);
    }

    @Override
    protected void onDestroy() {
        unRegisterReceiver();
        super.onDestroy();
    }

    /**
     * token过期，重新登录
     */
    private void reLogin() {
        quitAndLogin();
    }

    private class CusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            LogUtil.log("MainActivity onReceive action " + action);
            if (ACTION_NEED_LOGIN.equals(action)) {
                reLogin();
            }
        }
    }
}
